import traceback

from com.util.loggingUtil import Logs
from com.util.singletonUtil import Singleton
import requests
import json


class HttpRequest(Singleton):
    Log = Logs()

    def http_request(self, method, url, jsonp=None, headers=None, data=None):
        """
         "POST" json - application/json
         "POST" data - application/x-www-form-urlencoded
        """
        global res
        try:
            if method.upper() == "POST":
                res = requests.post(url, json=jsonp, headers=headers, data=data)
            if method.upper() == 'GET':
                res = requests.get(self.get_url_format(url=url, params=jsonp), headers=headers)
            if method.upper() == 'DELETE':
                res = requests.delete(url=url, json=jsonp, headers=headers, data=data)
            if method.upper() == 'PUT':
                res = requests.put(url=url, json=jsonp, headers=headers, data=data)
            # self.Log.info(f'【{method}】请求url【{url}】,\n '
            #             f'------param:【{jsonp}】，data:【{data}】,header【{headers}】,\n'
            #             f'------result:【{res.text}】')
        except Exception as e:
            self.Log.error(f'【{method}】请求url【{url}】,\n '
                           f'------param:【{jsonp}】，data:【{data}】,header【{headers}】,\n'
                           f'------error:【{traceback.format_exc()}】')
            return None
        # 返回结果
        if self.is_json(res.text):
            # 返回dict
            return json.loads(res.text)
        else:
            # 返回str
            return res.text

    # 判断是否是json 格式的数据
    def is_json(self, text):
        try:
            json.loads(text)
        except ValueError as e:
            return False
        return True

    # 拼接url字符串
    def get_url_format(self, url=None, params=None):  # 缺省参数放到最后
        """
        拼接Get请求参数
       :param url: 源url
       :param params: 参数dict
       :return: 拼接的url
       """
        if params:
            if not isinstance(params, dict):
                raise Exception('params必须是字典')  # 不是字典格式抛出异常
            url += '?' + '&'.join(
                [str(key) + '=' + str(value) for key, value in params.items()])  # params不为空，加上?key1=value1&key2=value2
        return url
